<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="投递者ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入投递者ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="漂流瓶类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
          <el-option label="❤️感谢瓶" value="0" />
          <el-option label="💬倾诉瓶" value="1" />
          <el-option label="🎁祝福瓶" value="2" />
          <el-option label="💡奇思妙想瓶" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="漂流瓶状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="漂流中" value="0" />
          <el-option label="被捞起" value="1" />
          <el-option label="推荐" value="2" />
          <el-option label="已屏蔽" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="点赞数量" prop="likeCount">
        <el-input
          v-model="queryParams.likeCount"
          placeholder="请输入点赞数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:bottle:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-lock"
          size="mini"
          :disabled="multiple"
          @click="handleBatchBlock"
        >批量屏蔽</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-circle-check"
          size="mini"
          :disabled="multiple"
          @click="handleBatchApprove"
        >批量审核通过</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:bottle:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bottleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="漂流瓶ID" align="center" prop="id" width="100" />
      <el-table-column label="投递者ID" align="center" prop="userId" width="100" />
      <el-table-column label="投递者昵称" align="center" prop="userNickname" width="120" />
      <el-table-column label="投递者手机号" align="center" prop="userPhone" width="130" />
      <el-table-column label="漂流瓶内容" align="center" prop="content" width="300" show-overflow-tooltip />
      <el-table-column label="漂流瓶类型" align="center" prop="type">
        <template slot-scope="scope">
          <span v-if="scope.row.type == 0">❤️感谢瓶</span>
          <span v-else-if="scope.row.type == 1">💬倾诉瓶</span>
          <span v-else-if="scope.row.type == 2">🎁祝福瓶</span>
          <span v-else-if="scope.row.type == 3">💡奇思妙想瓶</span>
          <span v-else>{{ scope.row.type }}</span>
        </template>
      </el-table-column>
      <el-table-column label="点赞数量" align="center" prop="likeCount">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.likeCount >= 100" type="danger" effect="dark">
            <i class="el-icon-medal"></i> {{ scope.row.likeCount }}
          </el-tag>
          <el-tag v-else-if="scope.row.likeCount >= 50" type="warning" effect="dark">
            <i class="el-icon-trophy"></i> {{ scope.row.likeCount }}
          </el-tag>
          <el-tag v-else-if="scope.row.likeCount >= 20" type="success" effect="plain">
            <i class="el-icon-star-on"></i> {{ scope.row.likeCount }}
          </el-tag>
          <el-tag v-else-if="scope.row.likeCount >= 10" type="primary" effect="plain">
            <i class="el-icon-thumb"></i> {{ scope.row.likeCount }}
          </el-tag>
          <el-tag v-else-if="scope.row.likeCount > 0" type="info" effect="plain">
            👍 {{ scope.row.likeCount }}
          </el-tag>
          <span v-else style="color: #909399;">{{ scope.row.likeCount || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="漂流瓶状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 0" type="info">漂流中</el-tag>
          <el-tag v-else-if="scope.row.status == 1" type="success">被捞起</el-tag>
          <el-tag v-else-if="scope.row.status == 2" type="warning">推荐</el-tag>
          <el-tag v-else-if="scope.row.status == 3" type="danger">已屏蔽</el-tag>
          <span v-else>{{ scope.row.status }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-if="scope.row.status != 3"
            size="mini"
            type="text"
            icon="el-icon-lock"
            @click="handleBlock(scope.row)"
            style="color: #F56C6C;"
          >屏蔽</el-button>
          <el-button
            v-else
            size="mini"
            type="text"
            icon="el-icon-unlock"
            @click="handleUnblock(scope.row)"
            style="color: #67C23A;"
          >解除屏蔽</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改漂流瓶对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="投递者ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入投递者ID" />
        </el-form-item>
        <el-form-item label="漂流瓶内容" prop="content">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="漂流瓶类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择漂流瓶类型">
            <el-option label="❤️感谢瓶" :value="0" />
            <el-option label="💬倾诉瓶" :value="1" />
            <el-option label="🎁祝福瓶" :value="2" />
            <el-option label="💡奇思妙想瓶" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="漂流瓶状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择漂流瓶状态">
            <el-option label="漂流中" :value="0" />
            <el-option label="被捞起" :value="1" />
            <el-option label="推荐" :value="2" />
            <el-option label="已屏蔽" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="点赞数量" prop="likeCount">
          <el-input v-model="form.likeCount" placeholder="请输入点赞数量" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBottle, getBottle, delBottle, addBottle, updateBottle } from "@/api/system/bottle"
import { getMuser } from "@/api/system/muser"

export default {
  name: "Bottle",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 漂流瓶表格数据
      bottleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        content: null,
        type: null,
        likeCount: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "投递者ID，关联user表不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "漂流瓶内容不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "漂流瓶类型：0❤️感谢瓶，1?倾诉瓶，2?祝福瓶，3?奇思妙想瓶不能为空", trigger: "change" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询漂流瓶列表 */
    async getList() {
      this.loading = true
      try {
        const response = await listBottle(this.queryParams)
        this.bottleList = response.rows
        this.total = response.total
        
        // 获取每个漂流瓶的投递者信息
        await this.fetchUserInfo()
        
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    },
    /** 获取用户信息 */
    async fetchUserInfo() {
      // 收集所有唯一的用户ID
      const userIds = [...new Set(this.bottleList.map(item => item.userId).filter(id => id))]
      
      // 批量获取用户信息
      const userPromises = userIds.map(userId => {
        return getMuser(userId).then(res => ({
          userId: userId,
          nickname: res.data.nickname,
          phone: res.data.phone
        })).catch(() => ({
          userId: userId,
          nickname: '未知',
          phone: '-'
        }))
      })
      
      const users = await Promise.all(userPromises)
      
      // 创建用户信息映射
      const userMap = {}
      users.forEach(user => {
        userMap[user.userId] = user
      })
      
      // 将用户信息添加到漂流瓶数据中，并触发响应式更新
      this.bottleList = this.bottleList.map(bottle => {
        const user = userMap[bottle.userId]
        return {
          ...bottle,
          userNickname: user ? user.nickname : '未知',
          userPhone: user ? user.phone : '-'
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        content: null,
        type: null,
        likeCount: null,
        status: null,
        createTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加漂流瓶"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getBottle(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改漂流瓶"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBottle(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addBottle(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 屏蔽按钮操作（单个） */
    handleBlock(row) {
      this.$modal.confirm('是否确认屏蔽该漂流瓶？').then(() => {
        return this.updateBottleStatus(row.id, 3)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("屏蔽成功")
      }).catch(() => {})
    },
    /** 解除屏蔽按钮操作 */
    handleUnblock(row) {
      this.$modal.confirm('是否确认解除屏蔽该漂流瓶？解除后将恢复为漂流中状态。').then(() => {
        return this.updateBottleStatus(row.id, 0)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("解除屏蔽成功")
      }).catch(() => {})
    },
    /** 批量屏蔽按钮操作 */
    handleBatchBlock() {
      const ids = this.ids
      this.$modal.confirm('是否确认屏蔽选中的漂流瓶？').then(() => {
        const promises = ids.map(id => this.updateBottleStatus(id, 3))
        return Promise.all(promises)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("批量屏蔽成功")
      }).catch(() => {})
    },
    /** 批量审核通过按钮操作 */
    handleBatchApprove() {
      const ids = this.ids
      this.$modal.confirm('是否确认审核通过选中的漂流瓶？审核通过后将恢复为漂流中状态。').then(() => {
        const promises = ids.map(id => this.updateBottleStatus(id, 0))
        return Promise.all(promises)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("批量审核通过成功")
      }).catch(() => {})
    },
    /** 更新漂流瓶状态 */
    updateBottleStatus(id, status) {
      return getBottle(id).then(response => {
        const bottleData = response.data
        bottleData.status = status
        return updateBottle(bottleData)
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/bottle/export', {
        ...this.queryParams
      }, `bottle_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
